package com.isnotlocus.gulimail.product.service.impl;

import com.IsnotLocus.common.utils.to.es.SkuEsModel;
import com.isnotlocus.common.utils.R;
import com.isnotlocus.common.utils.to.SkuReductionTo;
import com.isnotlocus.common.utils.to.SpuBoudTo;
import com.isnotlocus.gulimail.product.Feign.SpuBoudFeignService;
import com.isnotlocus.gulimail.product.entity.*;
import com.isnotlocus.gulimail.product.service.*;
import com.isnotlocus.gulimail.product.vo.*;
import jdk.internal.util.xml.impl.Attrs;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isnotlocus.common.utils.PageUtils;
import com.isnotlocus.common.utils.Query;

import com.isnotlocus.gulimail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;


@Service()
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SpuBoudFeignService spuBoudFeignService;


    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    //TODO 其他更多细节，高级部分解决
    @Transactional
    @Override
    public void SaveSpuInfo(SpuSaveVO spuSaveVO) {
        //1.保存spu的基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBasicsSpuInfoMsg(spuInfoEntity);
        //2.保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //把数组拼接起来，中间是 "," 隔开
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVO.getDecript()));
        spuInfoDescService.saveSpuInfoDescEntity(spuInfoDescEntity);
        //3.保存spu的图片集  pms_spu_images
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);
        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> BaseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> collect = BaseAttrs.stream().map((item) -> {
            ProductAttrValueEntity attr = new ProductAttrValueEntity();
            attr.setAttrId(item.getAttrId());
            attr.setAttrName(attrService.getById(item.getAttrId()).getAttrName());
            attr.setAttrValue(item.getAttrValues());
            attr.setQuickShow(item.getShowDesc());
            attr.setSpuId(spuInfoEntity.getId());
            return attr;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(collect);
        //5.保存当前spu对应的积分信息: gulimail_sms -> sms_spu_bounds
        Bounds bounds = spuSaveVO.getBounds();
        SpuBoudTo spuBoudTo = new SpuBoudTo();
        BeanUtils.copyProperties(bounds, spuBoudTo);
        spuBoudTo.setSpuId(spuInfoEntity.getId());
        R r = spuBoudFeignService.SaveSpuCoupon(spuBoudTo);
        if (r.getCode() == 0) {
            System.out.println("没有任何异常！！");
        } else {
            log.error("保存远程优惠信息失败！！！");
        }
        //6.保存当前spu对应的所有sku信息
        //6.1） sku的基本信息：pms_sku_info
        List<Skus> SKus = spuSaveVO.getSkus();
        if (SKus != null && SKus.size() > 0) {
            SKus.forEach((item) -> {
                /**    private String skuName;
                 *     private BigDecimal price;
                 *     private String skuTitle;
                 *     private String skuSubtitle;
                 */
                String defaultImg = "";
                for (Images i : item.getImages()) {
                    if (i.getDefaultImg() == 1) {
                        defaultImg = i.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L); //销量
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //6.2)  sku的图片信息：pms_sku_images
                List<SkuImagesEntity> ImagesEntities = item.getImages().stream().map((img) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，false就是剔除
                    return !StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveSKuImgBatch(ImagesEntities);
                //6.3)  sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> SkuSaleAttrValueEntities = attrs.stream().map((attr) -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveSkuSaleAttrValue(SkuSaleAttrValueEntities);
                //6.4)  sku的优惠信息、满减信息：gulimail_sms-> sms_sku_ladder / sms_sku_full_reduction /sms_member_price
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, reductionTo);
                reductionTo.setSkuId(skuId);
                //BigDecimal的比较，-1就是小于   0就是等于   1就是大于
                if (reductionTo.getFullCount() > 0 || reductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = spuBoudFeignService.saveSkuReduction(reductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存spu积分信息失败！！！");
                    }
                }
            });
        }


    }

    public void saveBasicsSpuInfoMsg(SpuInfoEntity spuInfoEntity) {
        //Iservice 和basemapper 的insert方法保存后，都会对该实体类进行本质的改变，就是
        //会改变进来插入的实体类，就是进来如果没有ID，那么插入如果有自增就会，进来操作的对象就会有自增后的ID
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils selectByBatchs(Map<String, Object> map) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
        System.out.println(map);
        String key=(String) map.get("key");
        if(StringUtils.isNotEmpty(key) && !key.equalsIgnoreCase("") ){
               wrapper.and((item)->{
                   item.eq("id",key).or().like("spu_name",key);
               });
        }
        if(map.get("status")!=null && !map.get("status").toString().equalsIgnoreCase("")){
            int status= Integer.parseInt(map.get("status").toString()) ;
            wrapper.eq("publish_status",status);
        }


        if(map.get("brandId")!=null && !map.get("brandId").toString().equalsIgnoreCase("")&&Long.valueOf(map.get("brandId").toString())!=0){
            Long BrandId= Long.valueOf(map.get("brandId").toString()) ;
            wrapper.eq("brand_id",BrandId);
        }


        if(map.get("catelogId")!=null && !map.get("catelogId").toString().equalsIgnoreCase("")){
            Long categoryId= Long.valueOf(map.get("catelogId").toString());
            wrapper.eq("catalog_id",categoryId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(map),
                wrapper);
        return new PageUtils(page);
    }

    /**
     * 商品上架共功能
     * @param spuid
     */
    @Override
    public void up(Long spuid) {
        List<SkuEsModel> skuEsModels=new ArrayList<SkuEsModel>();
        //1.查询当前spuid对应的所有sku信息、品牌和名字
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySkuId(spuid);

        //TODO 4.查询当前sku的所有可以被检索规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuid);
        List<Long> attrIds = baseAttrs.stream().map(attr->{
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> attrsIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet =new HashSet<>();

        List<SkuEsModel.Attrs> attrs = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        //2.封装sku的信息
        skus.stream().map(sku->{
            SkuEsModel skuEsModel=new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);

            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setBrandImg(sku.getSkuDefaultImg());
            //TODO 1.发送远程调用，库存系统查询是否有库存

            //TODO 2.热度评分0
            skuEsModel.setHotScore(0L);
            //TODO 3.查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 发给检索服务

    }

}